package com.edu.service.impl;

import com.edu.bean.User;
import com.edu.mapper.UserMapper;
import com.edu.service.UserService;
import org.apache.ibatis.session.SqlSession;
import org.springframework.jdbc.object.SqlCall;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Connection;
import java.util.List;


@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Override
    public List<User> getAllUser() {
        return userMapper.selectAllUser();
    }

    @Override
    public int addUser(User user) {
        return userMapper.insertUser(user);
    }

    @Override
//    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout = 5)
    public int transferBalance(int userId1, int userId2, double balance) {

        User user1 = userMapper.selectUserById(userId1);
        User user2 = userMapper.selectUserById(userId2);

        if (user2 == null) {
            return -2;
        }
        if (user1.getBalance() < balance) {
            return -1;
        }
        int r1 = userMapper.decreaseBalance(userId1, balance);
//        String str = null;
//        System.out.println(str.length());
//        try {
//            Thread.sleep(7000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        int r2 = userMapper.increaseBalance(userId2, balance);

        return r1 ==  1&& r2 == 1? 1: 0;
    }
}
